# coding=utf-8

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.utils import shuffle


class Perceptron(object):

    def __init__(self, eta=0.01, n_iter=10):
        self.eta = eta
        self.n_iter = n_iter

    def fit(self, X, y):
        # 样本的特性的集合
        self.w_ = np.zeros(1 + X.shape[1])
        # 错误的集合
        self.errors_ = []
        for _ in range(self.n_iter):
            errors = 0
            for xi, target in zip(X, y):
                update = self.eta * (target - self.predict(xi))
                self.w_[1:] += update * xi
                self.w_[0] += update
                errors += int(update != 0.0)
            self.errors_.append(errors)
        return self

    def net_input(self, X):
        return np.dot(X, self.w_[1:]) + self.w_[0]

    def predict(self, X):
        return np.where(self.net_input(X) >= 0.0, 1, -1)

df = pd.read_csv(
    'iris.data.txt', header=None)

right = 0.0
count = 0
for _ in xrange(100):
    df = shuffle(df)
    y2 = df.iloc[100:, 4].values
    y2 = np.where(y2 == 'Iris-setosa', -1, 1)
    # print y2
    # print "#########################"
    y = df.iloc[:100, 4].values
    y = np.where(y == 'Iris-setosa', -1, 1)
    X = df.iloc[:100, :3].values

    ppn = Perceptron(eta=.1, n_iter=1)
    ppn.fit(X, y)
    i = 0
    for x in df.iloc[100:, :3].values:
        if ppn.predict(x) == y2[i]:
            right += 1
        i += 1
        count +=1
    print '正确率：', right / count
